from itsdangerous import TimedJSONWebSignatureSerializer
from itsdangerous import BadData
from django.conf import settings

def generate_access_token(open_id):
    # QQ 登录保存用户数据的 token 有效期
    # settings.SECRET_KEY: 加密使用的秘钥
    # 过期时间: 600s = 10min
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires_in=600)
    # 数据字典
    data = {'open_id': open_id}
    # 对字典加密
    token_byte = serializer.dumps(data)
    # 解码
    token = token_byte.decode()
    return token


def check_access_token(access_token):
    """
    检验用户传入的 token
    :param token: token
    :return: openid or None
    """
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires_in=600)
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('open_id')
